package com.zhenyi.youqu.miniapp;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.cjw.model.DBMap;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.youqu.common.model.YqApp;
import com.youqu.common.model.YqCategory;
import com.youqu.common.model.YqGroup;
import com.youqu.common.model.YqItem;
import com.youqu.common.model.YqProduct;
import com.youqu.common.model.YqProductFormat;
import com.youqu.common.model.YqUser;
import com.youqu.common.model.YqUserSubscribe;
import com.zhenyi.youqu.core.YQConfig;
import com.zhenyi.youqu.core.YQMiniAppController;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;

/**
 * 首页
 * 
 * @author cen
 *
 */
public class HomeController extends YQMiniAppController {

	// private int itemsSize() {
	// String key = APP_ID + "_itemsSize";
	// Integer size = cache.get(key);
	// if (size != null) {
	// return size;
	// }
	// // size = YqItem.dao.findAll().size();
	// SqlPara sp = db.getSqlPara("YQFindItems");
	// List<Record> list = db.find(sp);
	// size = list.size();
	// cache.setex(key, 7200, size);
	// return size;
	// }

	/**
	 * 找到有趣最大的id
	 * 
	 * @return
	 */
	private Long getMaxId() {
		String key = YQ_APP_ID + "_itemsMaxId";
		Long maxId = cache.get(key);
		if (maxId != null) {
			return maxId;
		}
		Kv kv = Kv.by("ordered", 1);
		SqlPara sqlPara = db.getSqlPara("YQFindItems", kv);
		YqItem item = YqItem.dao.paginate(1, 1, sqlPara).getList().get(0);
		maxId = item.getId();
		cache.setex(key, 7200, maxId);
		return maxId;
	}

	/**
	 * 用redis 缓存所有id,随机抽取一个
	 * 
	 * @return
	 */
	public YqItem getRandomItemPro() {
		String key = YQConfig.KEY_ITEM_INDEX;
		Long size = cache.scard(key);
		if (size == 0) {
			yqUtils.updateItemIndex();
		}
		Long id = cache.srandmember(key);
		YqItem item = YqItem.dao.findById(id);
		if (item == null) {
			/**
			 * 如果找不到,就用最原始的随机算法
			 */
			cache.srem(key, id);
			return getRandomItem();
		}
		if (!item.canShow()) {
			/**
			 * 不允许显示
			 */
			cache.srem(key, id);
			return getRandomItem();
		}
		return item;
	}

	private YqItem getRandomItem() {
		// int size = itemsSize();
		Long maxId = getMaxId();
		Long id = RandomUtil.randomLong(1, maxId + 1);
		Kv kv = Kv.by("id", id);
		SqlPara sqlPara = db.getSqlPara("YQFindRanItem", kv);
		YqItem yqItem = YqItem.dao.findFirst(sqlPara);
		if (yqItem == null) {
			sqlPara = db.getSqlPara("YQFindRanItem", Kv.by("id", 1));
			List<YqItem> list = YqItem.dao.find(sqlPara);
			yqItem = list.get(RandomUtil.randomInt(0, list.size()));
		}

		// int randomIndex = RandomUtil.randomInt(0, size - 1);
		// SqlPara sqlPara = db.getSqlPara("YQFindItems");
		// System.out.println("size: " + size);
		// System.out.println("randomIndex: " + randomIndex);
		// System.out.println(sqlPara);
		// YqItem yqItem = YqItem.dao.find(sqlPara).get(randomIndex);

		// yqItem.setCover("http://lorempixel.com/400/300/");
		// yqItem.setTitle(RandomUtil.randomString(10));
		// yqItem.setIntro(RandomUtil.randomString(40));
		// yqItem.setSubscribeCount(RandomUtil.randomInt(8, 44));
		if (yqItem.getStartTime() != null) {
			DateTime start = new DateTime(yqItem.getStartTime());
			Date now = new Date();
			if (start.isAfterOrEquals(now)) {
				Long betweenDay = DateUtil.betweenDay(now, start, true);
				yqItem.put("daysToStart", betweenDay);
			}
		}

		YqUser user = getUser();
		if (user != null) {
			Long itemId = yqItem.getId();
			Long userId = user.getId();
			YqUserSubscribe userSubscribe = YqUserSubscribe.dao.findById(itemId, userId);
			yqItem.put("isSubscribe", userSubscribe == null ? 0 : 1);
		}
		return yqItem;
	}

	/**
	 * 随机拿一个有趣
	 */
	@Override
	public void index() {
		renderSuccess(getRandomItemPro());
	}

	/**
	 * 拿若干个有趣
	 */
	public void init() {
		int count = getParaToInt("count", 5);
		ArrayList<YqItem> list = new ArrayList<>();
		for (int i = 0; i < count; i++) {
			YqItem yqItem = getRandomItemPro();
			// yqItem.setCover("http://lorempixel.com/400/300/");
			// yqItem.setTitle(RandomUtil.randomString(10));
			// yqItem.setIntro(RandomUtil.randomString(40));
			// yqItem.setSubscribeCount(RandomUtil.randomInt(8, 44));
			list.add(yqItem);
		}
		renderSuccess(list);
	}

	/**
	 * 关注列表,日历
	 */
	public void subscribes() {
		// String startTime = getPara("startTime");
		// String endTime = getPara("endTime");
		String date = getPara("date");
		String keyword = getPara("keyword");
		YqUser user = getUser();
		Long userId = user.getId();
		Kv kv = Kv.by("userId", userId);
		// if (StrKit.notBlank(startTime, endTime)) {
		// kv.set("startTime", startTime);
		// kv.set("endTime", endTime);
		// }
		if (StrKit.notBlank(date)) {
			kv.set("startTime", DateUtil.beginOfMonth(DateUtil.parse(date)).toString("yyyy-MM-dd HH:mm:ss"));
			kv.set("endTime", DateUtil.endOfMonth(DateUtil.parse(date)).toString("yyyy-MM-dd HH:mm:ss"));
		}
		if (StrKit.notBlank(keyword)) {
			kv.set("keyword", keyword);
		}
		SqlPara sqlPara = db.getSqlPara("YQFindUserSubscribe", kv);
		Page<Record> pages = db.paginate(getPage(), PAGE_SIZE, sqlPara);
		for (Record record : pages.getList()) {
			if (record.get("startTime") != null) {
				DateTime start = new DateTime(record.getDate("startTime"));
				Date now = new Date();
				if (start.isAfterOrEquals(now)) {
					Long betweenDay = DateUtil.betweenDay(now, start, true);
					record.set("daysToStart", betweenDay);
				}

				if (record.get("endTime") != null) {
					DateTime end = new DateTime(record.getDate("endTime"));
					record.set("startTimeStr", start.toString("MM/dd"));
					if (end.year() == start.year() && end.month() == start.month()) {
						record.set("endTimeStr", end.toString("dd"));
					} else {
						record.set("endTimeStr", end.toString("MM/dd"));
					}
				}
			}
		}
		renderPage(pages);
	}

	/**
	 * 收藏商品列表 (/yq/user/subscribeProducts)
	 */
	@Deprecated
	public void subscribeProducts() {
		YqUser user = getUser();
		if (user == null) {
			renderFailure(401, "Please login");
			return;
		}
		Kv kv = Kv.create();
		kv.set("userId", user.getId());
		SqlPara sqlPara = db.getSqlPara("YQProductSubscribes", kv);
		Page<Record> pages = db.paginate(getPage(), PAGE_SIZE, sqlPara);
		renderPage(pages);
	}

	/**
	 * 喜欢 (/yq/user/subscribe)
	 */
	@Deprecated
	public void subscribe() {
		// YqUser user = getUser();
		// Long itemId = getParaToLong("itemId");
		// Long productId = getParaToLong("productId");
		// Long userId = user.getId();
		// if (itemId != null) {
		// YqUserSubscribe userSubscribe = YqUserSubscribe.dao.findById(itemId,
		// userId);
		// if (userSubscribe == null) {
		// userSubscribe = new YqUserSubscribe();
		// userSubscribe.setUserId(userId);
		// userSubscribe.setItemId(itemId);
		// userSubscribe.save();
		// }
		// } else if (productId != null) {
		// YqUserSubscribeProduct userSubscribeProduct =
		// YqUserSubscribeProduct.dao.findById(productId, userId);
		// if (userSubscribeProduct == null) {
		// userSubscribeProduct = new YqUserSubscribeProduct();
		// userSubscribeProduct.setUserId(userId);
		// userSubscribeProduct.setProductId(productId);
		// userSubscribeProduct.save();
		// }
		// }
		// renderSuccess();
		renderError(404);
	}

	/**
	 * 取消喜欢 (/yq/user/unsubscribe)
	 */
	@Deprecated
	public void unsubscribe() {
		// YqUser user = getUser();
		// Long itemId = getParaToLong("itemId");
		// Long productId = getParaToLong("productId");
		// Long userId = user.getId();
		// if (itemId != null) {
		// YqUserSubscribe userSubscribe = YqUserSubscribe.dao.findById(itemId,
		// userId);
		// if (userSubscribe == null) {
		// renderFailure(404, "not found");
		// return;
		// }
		// userSubscribe.delete();
		// } else if (productId != null) {
		// YqUserSubscribeProduct userSubscribeProduct =
		// YqUserSubscribeProduct.dao.findById(productId, userId);
		// if (userSubscribeProduct == null) {
		// renderFailure(404, "not found");
		// return;
		// }
		// userSubscribeProduct.delete();
		// }
		// renderSuccess();
		renderError(404);
	}

	/**
	 * 有趣详情
	 */
	@Override
	public void info() {
		YqUser user = getUser();
		Long userId = user.getId();
		Long itemId = getParaToLong("itemId");
		if (itemId == null) {
			renderError(404);
			return;
		}
		YqItem yqItem = YqItem.dao.findById(itemId);
		if (yqItem == null) {
			renderError(404);
			return;
		}

		DBMap map = new DBMap();
		yqItem.setSubscribeCount(yqItem.getSubscribeCount() + 1);
		yqItem.update();
		Long productId = yqItem.getProductId();
		if (productId == null) {
			// productId = getParaToLong("productId");
			if (productId == null) {
				map.put("item", yqItem);
				renderSuccess(map);
				return;
			}
		}
		YqProduct product = YqProduct.dao.findById(productId);
		if (product == null) {
			renderSuccess(yqItem);
			map.put("item", yqItem);
			return;
		}
		List<YqProductFormat> formats = product.getFormats(false);
		if (formats != null) {
			for (YqProductFormat format : formats) {
				format.set("fee", format.getInt("fee").floatValue() / 100);
			}
			product.put("formats", formats);
		}
		// yqItem.put("product", product);

		// SqlPara spFormat = db.getSqlPara("YQAdminProductFormat",
		// Kv.by("productId",
		// product.getId()));
		// List<Record> formats = db.find(spFormat);
		// if (formats != null && formats.size() > 0) {
		// product.set("sizes", formats);
		// }

		String shareTitle = product.getShareTitle();
		String shareImage = product.getShareImage();
		if (StrKit.notBlank(shareTitle)) {
			yqItem.setShareTitle(shareTitle);
		}
		if (StrKit.notBlank(shareImage)) {
			yqItem.setShareImage(shareImage);
		}
		Integer isGroup = product.getIsGroup();
		yqItem.put("isGroup", isGroup);
		yqItem.put("productId", productId);

		if (isGroup.equals(1)) {
			Kv kv = Kv.by("productId", productId);
			SqlPara sqlPara = db.getSqlPara("YQFindProductPaidUser", kv);
			List<Record> records = db.paginate(1, 10, sqlPara).getList();
			yqItem.put("users", records);

			YqGroup group = YqGroup.dao.findJoinedGroup(userId, productId);
			if (group != null) {
				yqItem.put("groupId", group.getId());
			}
		}

		map.put("product", product);
		map.put("item", yqItem);
		renderSuccess(map);
	}

	public void calendar() {
		// String startTime = getPara("startTime");
		// String endTime = getPara("endTime");
		String date = getPara("date");

		Kv kv = Kv.create();
		// if (StrKit.notBlank(startTime, endTime)) {
		// kv.set("startTime", startTime);
		// kv.set("endTime", endTime);
		// }
		if (StrKit.notBlank(date)) {
			kv.set("startTime", DateUtil.beginOfMonth(DateUtil.parse(date)).toString("yyyy-MM-dd HH:mm:ss"));
			kv.set("endTime", DateUtil.endOfMonth(DateUtil.parse(date)).toString("yyyy-MM-dd HH:mm:ss"));
		}
		SqlPara sqlPara = db.getSqlPara("YQFindCalendar", kv);
		Page<Record> pages = db.paginate(getPage(), PAGE_SIZE, sqlPara);
		for (Record record : pages.getList()) {
			if (record.get("startTime") != null) {
				DateTime start = new DateTime(record.getDate("startTime"));
				Date now = new Date();
				if (start.isAfterOrEquals(now)) {
					Long betweenDay = DateUtil.betweenDay(now, start, true);
					record.set("daysToStart", betweenDay);
				}

				if (record.get("endTime") != null) {
					DateTime end = new DateTime(record.getDate("endTime"));
					record.set("startTimeStr", start.toString("MM/dd"));
					if (end.year() == start.year() && end.month() == start.month()) {
						if (end.dayOfMonth() != start.dayOfMonth()) {
							record.set("endTimeStr", end.toString("dd"));
						}
					} else {
						record.set("endTimeStr", end.toString("MM/dd"));
					}
				}
			}
		}
		renderPage(pages);
	}

	/**
	 * 获取category列表
	 */
	public void categories() {
		YqApp app = getApp();
		Kv kv = getSimpleKv();
		kv.set("appId", app.getId());
		SqlPara sqlPara = db.getSqlPara("YQCategories", kv);
		List<YqCategory> list = YqCategory.dao.find(sqlPara);
		renderResult(list);
	}

	/**
	 * 获取category详情
	 */
	public void categoryInfo() {
		Long categoryId = getParaToLong("categoryId");
		if (categoryId == null) {
			renderFailure("category id is required");
			return;
		}
		YqCategory category = YqCategory.dao.findById(categoryId);
		if (category == null) {
			renderError(404);
			return;
		}
		renderResult(category);
	}

	/**
	 * 首页banners
	 */
	public void banners() {
		YqApp app = getApp();
		Kv kv = Kv.create();
		kv.set("appId", app.getId());
		SqlPara sqlPara = db.getSqlPara("YQFindProducts", kv);
		List<Record> items = db.paginate(getPage(), 5, sqlPara).getList();
		renderSuccess(items);
	}

	/**
	 * 首页限时团购
	 */
	public void groups() {
		YqApp app = getApp();
		Kv kv = Kv.create();
		kv.set("appId", app.getId());
		SqlPara sqlPara = db.getSqlPara("YQTimeLimitGroup");
		List<Record> items = db.paginate(getPage(), 5, sqlPara).getList();
		for (Record record : items) {
			record.set("endTimestamp", record.getDate("endTime").getTime());
		}
		renderSuccess(items);
	}
}
